<%@ Language=VBScript %>
<!--#include file="../connections/connectVB.asp"-->
<!-- #include file="Utility/freeASPUploadLibrary.asp" -->
<%
'Get ProductById
Dim ProdName, ProdPrice,Size, Description, ProdId,CatId, Images
ProdId = Request.QueryString("ProdId")
Function GetProdById

Set Recordset = Server.CreateObject("ADODB.Recordset")
Dim sql 
sql = "Select a.*, b.CategoryID from Product a join Category b on a.CategoryID = b.CategoryID where ProductID =" + ProdId
Recordset.Open sql,conn

ProdName = Recordset("ProductName")
ProdPrice = Recordset("Price")
Size = Recordset("Size")
Description = Recordset("Description")
CatId = Recordset("CategoryID")
Images = Recordset("Image")

'Close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
if conn.State =  adStateOpen then
        conn.Close
 End If
End Function
%>

<% 
 'Declare upload folder
 Dim uploadsDirVar
 uploadsDirVar = Server.MapPath("../Upload/ImageProd")

 
'Insert Image
function SaveFiles
    Dim Upload, fileName, fileSize, ks, i, fileKey, ImgName
	Dim hdProdImage
	
	Set Upload = New FreeASPUpload
    Upload.Save(uploadsDirVar)	
	hdProdImage =  Upload.Form("hdProdImage")

if (hdProdImage <> "" or hdProdImage <> null) then	
	' If something fails inside the script, but the exception is handled
	If Err.Number<>0 then Exit function

    SaveFiles = ""
    ks = Upload.UploadedFiles.keys

    if (UBound(ks) <> -1) then
        'SaveFiles = "<B>Files uploaded:</B> "		
        for each fileKey in Upload.UploadedFiles.keys
			'Upload.UploadedFiles(fileKey).FileName = "Nick.jpg"
            'SaveFiles = SaveFiles & Upload.UploadedFiles(fileKey).FileName & " (" & Upload.UploadedFiles(fileKey).Length & "B) "			
			ImgName = Upload.UploadedFiles(fileKey).FileName	
        next		
    end if
end if

'Update Product 
	Dim pName
	Dim CatId
	Dim pPrice	
	Dim ImgUrl
	Dim pSize
	Dim pDes
	
	pName = Upload.Form("pName")
	CatId = Upload.Form("CatID")
	pPrice = Upload.Form("pPrice")
	ImgUrl = Upload.Form("ProdImg")
	pSize = Upload.Form("pSize")
	pDes = Upload.Form("pDes")
	pID = Upload.Form("ProdID")
	
	'if Discount = "" then
		'Discount = ""
	'End if
	
	
	'Don't update image if not specify new image.	
	if (hdProdImage = "" or hdProdImage = null) then
		sql = "UPDATE Product SET ProductName='"+pName+"',[CategoryID]="+CatId+",[Price]="+pPrice+",[Size]="+pSize+",[Description]='"+pDes+"' WHERE ProductID="+pID
		
		else 'Update image if new image is spcified
	sql = "UPDATE Product SET ProductName='"+pName+"',[CategoryID]="+CatId+",[Price]="+pPrice+",[Image]='"+ImgName+"',[Size]="+pSize+",[Description]='"+pDes+"' WHERE ProductID="+pID
	End if
	
	conn.Execute(sql)
	
	if conn.State =  adStateOpen then
        conn.Close
    End If	
	
Response.Redirect("product.asp")
end function
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/AdminLayout.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width", initial-scale=1, user-scalable=no/>
<!-- InstanceBeginEditable name="doctitle" -->
<title>Admin - Product Insert</title>
<!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->

<!--Start - CSS-->
<!--<link rel="stylesheet" href="../css/bootstrap.min.css">-->
<!--<link rel="stylesheet" href="css/flexslider.css" type="text/css" />-->
<link rel="stylesheet" href="../Validation/vendor/bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="../css/bootstrap-theme.min.css">
<link rel="stylesheet" href="../Validation/dist/css/bootstrapValidator.css"/>
<link rel="stylesheet" href="../css/default.min.css" /><!-- css for editor-->
<link rel="stylesheet" href="../css/jquery.dataTables.css"><!-- css for dataTable-->
<link rel="stylesheet" href="../css/admstyle.css" />
<!--End - CSS-->

<!--Start - External Script-->
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" src="../Validation/dist/js/bootstrapValidator.js"></script>
<script type="text/javascript" src="../js/jquery.sceditor.bbcode.min.js"></script> <!-- script for editor-->
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>  <!--Script for dataTable-->
<script type="text/javascript" src="../js/adm_custom_script.js"></script> <!--Custom Script for Admin Template-->
<!--End - External Script-->


<!--Start Custome Javascript-->

<!--End Custome Javascript-->
</head>

<body>
<div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
    <a class="navbar-brand " href="../index.asp">Home</a> </div>
  <div class="navbar-collapse collapse navbar-responsive-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="admCatList.asp">Category</a></li>
      <li class=""><a href="AdmProdList.asp">Product</a></li>
      <li><a href="AdmProdComments.asp">Comments</a></li>
      <li><a href="AdmProdOrder.asp">Orders</a></li>
      <li><a href="admStatistic.asp">Statistic</a></li>
    <!-- <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Members <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Admin</a></li>
          <li><a href="#">Customers</a></li>
        </ul>
      </li>-->
    </ul>
   <!-- <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>-->
  </div>
</div>
<div class="container-fluid wrapper_admin_content">
<img class="ico_logo" src="../images/slogan.gif"/>
<!-- InstanceBeginEditable name="EditRegion3" -->
  <%  
  	if Request.ServerVariables("REQUEST_METHOD") = "POST" then  		 
		 response.write SaveFiles()
	elseif Request.ServerVariables("REQUEST_METHOD") = "GET" then
		response.write GetProdById		 
	end if
	
  %>
  <form ACTION="AdmProdUpdate.asp" enctype="multipart/form-data"  name="fmProdInsert" id="fmProdInsert" METHOD="POST" class="form-horizontal" onsubmit="return onSubmitForm();" >
    <fieldset>
      <legend>Update Product</legend>
      <div class="form-group">
        <label for="Name" class="col-lg-2 control-label">Product Name</label>
        <div class="col-lg-10">
          <input type="hidden" id="ProdId" name="ProdId" value="<% Response.Write(ProdId)%>"/>
          <input type="text" class="form-control" name="ProdName" id="ProdName" placeholder="Product Name" autocomplete="off" value="<% Response.Write(ProdName)%>">
        </div>
      </div>
      <div class="form-group">
        <label class="col-lg-2 control-label">Gender</label>
        <input type="hidden" id="hdGender" value="<%Response.Write(Gender)%>"/>
        <div class="col-lg-10">
          <div class="radio">
            <label>
              <input type="radio" name="Gender" id="GenderMale" value="1"  onclick="getCatbyGender(this.value)">
              Male </label>
          </div>
          <div class="radio">
            <label>
              <input type="radio" name="Gender" id="GenderFemale" value="0" onclick="getCatbyGender(this.value)" >
              Female </label>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label for="Name" class="col-lg-2 control-label">Category Name</label>
        <input type="hidden" id="hdCategory" value="<% Response.Write(CatId)%>"/>
        <div class="col-lg-10">
          <select id ="CatList" name="CatList"  class="form-control">
          </select>
        </div>
      </div>   
      <div class="form-group">
        <label for="Category" class="col-lg-2 control-label">Image</label>     
        <div class="col-lg-10">       
          <input name="ProdImg" id="ProdImg" class="form-control" type="file" >
   
          <input type="hidden" name="hdProdImage" id="hdProdImage" value="" />
        </div>
      </div>
      
        <div class="form-group">
        	<label for="Category" class="col-lg-2 control-label"></label> 
        <div class="col-lg-10">
        	<img style="width:50%" src="../Upload/Products/<%Response.Write(Images)%>"/> 
        </div>
      </div>
      
      <div class="form-group">
        <label for="Category" class="col-lg-2 control-label">Price ($USD)</label>
        <div class="col-lg-10">
          <input type="text" class="form-control" autocomplete="off" name="Price" id="Price" placeholder="Price" value="<% Response.Write(ProdPrice)%>">
        </div>
      </div>
      <div class="form-group">
        <label for="Category" class="col-lg-2 control-label">Arrival Date</label>
        <div class="col-lg-10">
          <input type="date" class="form-control" autocomplete="off" name="ArrivalDate" id="ArrivalDate" value="<% Response.Write(ProdDate)%>">
        </div>
      </div>
      <div class="form-group">
        <label for="Discount" class="col-lg-2 control-label">Discount</label>
        <div class="col-lg-10">
          <select  name="Discount" value="<%Response.Write(Discount)%>" id="Discount" class="form-control">
            <option value="0">0%</option>
            <option value="10">10%</option>
            <option value="20">20%</option>
            <option value="30">30%</option>
            <option value="40">40%</option>
            <option value="50">50%</option>
            <option value="60">60%</option>
            <option value="70">70%</option>
            <option value="80">80%</option>
            <option value="90">90%</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="Category" class="col-lg-2 control-label" >Excerpt</label>
        <div class="col-lg-10">
          <textarea class="form-control" name="Excerpt" id="Excerpt" autocomplete="off" placeholder="Excerpt"><% Response.Write(Excerpt)%>
</textarea>
        </div>
      </div>
      <div class="form-group">
        <label for="Category" class="col-lg-2 control-label" >Description</label>
        <div class="col-lg-10"> 
          <!-- <input type="text" class="form-control" autocomplete="off" name="Description" id="Description" placeholder="Description">-->
          <textarea class="form-control" autocomplete="off" name="Description" id="Description" placeholder="Description"><% Response.Write(Description)%>
</textarea>
        </div>
      </div>
      <div class="form-group">
        <div class="col-lg-10 col-lg-offset-2"> <a class="btn btn-default" href="AdmProdList.asp">Back</a>
          <button type="submit" class="btn btn-danger">Submit</button>
        </div>
      </div>
    </fieldset>
    <input type="hidden" name="MM_insertProd" value="insertProd" />
  </form>
  
  <!--<a id="nick" onclick="onSubmitForm();">test</a> --><!-- InstanceEndEditable -->

</div>

</body>
<!-- InstanceEnd --></html>
<script type="text/javascript">
$(document).ready(function() {
	
	//Get Value for Discount field
	$("select#Discount option").each(function(){
			if($(this).attr('value') == $("select#Discount").attr('value')){
				$(this).attr('selected','selected');
				}
		});
	
	//Get Value for Gender Field
	if($("#hdGender").attr('value') == "False"){
		$("#GenderFemale").attr('checked','true')
		}
	else {
		$("#GenderMale").attr('checked','true')
		}
		
	//Get Value for Category
	if($("#GenderFemale").attr('checked') == "checked"){
		getCatbyGender('0');
		
	}
	
	if ($("#GenderMale").attr('checked') == "checked"){
		getCatbyGender(1);
	}
	
	//alert($("select#CatList option:eq(2)").html())
	
	
	
	
	
    // Generate a simple captcha
    function randomNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    };
    $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));

    $('#fmProdInsert').bootstrapValidator({
//        live: 'disabled',
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            ProdName: {
                validators: {
                    notEmpty: {
                        message: 'Product Name is required and cannot be empty'
                    }
                }
            },
            CatList: {
                validators: {
                    notEmpty: {
                        message: 'Category is required and cannot be empty'
                    }
                }
            },
			//ProdImg: {
//                validators: {
//                    notEmpty: {
//                        message: 'Product Image is required and cannot be empty'
//                    }
//                }
//            },
			Price: {
                validators: {
                    notEmpty: {
                        message: 'The Price is required and cannot be empty'
                    },
					regexp: {
                        regexp: /^[1-9]\d{0,4}$/,
                        message: 'The Price can only consist of 4 number and the first number is not 0'
                    }
                }
            },
			ArrivalDate: {
                validators: {
                    notEmpty: {
                        message: 'The Product arrival date is required and cannot be empty'
                    }
                }
            },
			Excerpt: {
                validators: {
                    notEmpty: {
                        message: 'The Excerpt is required and cannot be empty'
                    }
                }
            },
			Description: {
                validators: {
                    notEmpty: {
                        message: 'The Description is required and cannot be empty'
                    }
                }
            },
            username: {
                message: 'The username is not valid',
                validators: {
                    notEmpty: {
                        message: 'The username is required and cannot be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: 'The username must be more than 6 and less than 30 characters long'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    },
                    // remote: {
                    //     url: 'remote.php',
                    //     message: 'The username is not available'
                    // },
                    different: {
                        field: 'password',
                        message: 'The username and password cannot be the same as each other'
                    }
                }
            },
            email: {
                validators: {
                    emailAddress: {
                        message: 'The input is not a valid email address'
                    }
                }
            },
            password: {
                validators: {
                    notEmpty: {
                        message: 'The password is required and cannot be empty'
                    },
                    identical: {
                        field: 'confirmPassword',
                        message: 'The password and its confirm are not the same'
                    },
                    different: {
                        field: 'username',
                        message: 'The password cannot be the same as username'
                    }
                }
            },
            confirmPassword: {
                validators: {
                    notEmpty: {
                        message: 'The confirm password is required and cannot be empty'
                    },
                    identical: {
                        field: 'password',
                        message: 'The password and its confirm are not the same'
                    },
                    different: {
                        field: 'username',
                        message: 'The password cannot be the same as username'
                    }
                }
            },
            birthday: {
                validators: {
                    date: {
                        format: 'YYYY/MM/DD',
                        message: 'The birthday is not valid'
                    }
                }
            },
            Gender: {
                validators: {
                    notEmpty: {
                        message: 'The gender is required'
                    }
                }
            },
            'languages[]': {
                validators: {
                    notEmpty: {
                        message: 'Please specify at least one language you can speak'
                    }
                }
            },
            'programs[]': {
                validators: {
                    choice: {
                        min: 2,
                        max: 4,
                        message: 'Please choose 2 - 4 programming languages you are good at'
                    }
                }
            },
            captcha: {
                validators: {
                    callback: {
                        message: 'Wrong answer',
                        callback: function(value, validator) {
                            var items = $('#captchaOperation').html().split(' '), sum = parseInt(items[0]) + parseInt(items[2]);
                            return value == sum;
                        }
                    }
                }
            }
        }
    });

    // Validate the form manually
    $('#validateBtn').click(function() {
        $('#defaultForm').bootstrapValidator('validate');
    });

    $('#resetBtn').click(function() {
        $('#defaultForm').data('bootstrapValidator').resetForm(true);
    });	
	
	
//Start - Format Prod Date
var today = new Date($("#ArrivalDate").attr('value'));
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} 
if(mm<10){mm='0'+mm} 
//today = mm+'/'+dd+'/'+yyyy;
today = yyyy+'-'+mm+'-'+dd;
$('#ArrivalDate').attr('value', today);
});
//End - Format Prod Date

//Ajax Get Category by Gender 
function getCatbyGender(value)
{
	
if (value == "")
  {
  document.getElementById("CatList").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("CatList").innerHTML=xmlhttp.responseText;
	//alert($("select#CatList").html())
	
	//Get Value for Category Field
	$("select#CatList option").each(function(){
		
		if($(this).attr('value') == $("#hdCategory").attr('value')){
			$(this).attr('selected','selected')
		}
		})
    }
  }
xmlhttp.open("GET","Utility/getCatbyGender.asp?Gender="+value,true);
xmlhttp.send();


}


//Change Product Image Name to Unique
function onSubmitForm()
	{
		var nameString = jQuery("#ProdImg").val();
		var nameArray = nameString.split('\\');
		var name = nameArray[nameArray.length - 1];
		if(name != "")
		{
			name = name.substr(name.lastIndexOf("."));
			name = Date.parse(new Date())+name;
			jQuery("#hdProdImage").val(name) ;
			//jQuery("#ProdImg").val(name) ;	
			//alert($("#hdProdImage").val());	
		}
		else
			jQuery("#hdProdImage").val("") ;	
		return true;	
	}
	
	
	
</script>
<script>
$(function() {
    // Replace all textarea's
    // with SCEditor
    $("#Description").sceditor({
        plugins: "xhtml",
		width: '100%',
		height: '400px',
		style: "../css/jquery.sceditor.default.min.css"
    });
});
</script>